package com.walkline.travelassistant;

import java.util.Hashtable;

import org.json.me.JSONObject;
import org.json.me.JSONTokener;

import com.walkline.travelassistant.dao.TravelAssistantDirection;
import com.walkline.travelassistant.dao.TravelAssistantLocation;
import com.walkline.travelassistant.dao.TravelAssistantSuggestionResult;
import com.walkline.travelassistant.inf.Direction;
import com.walkline.travelassistant.inf.Location;
import com.walkline.travelassistant.inf.SuggestionResult;
import com.walkline.util.network.HttpClient;
import com.walkline.util.network.MyConnectionFactory;

public class TravelAssistantSDK
{
	protected HttpClient _http;

	public static TravelAssistantSDK getInstance() {return new TravelAssistantSDK();}

	protected TravelAssistantSDK() {_http = new HttpClient(new MyConnectionFactory());}

	private Location convertIp2Location(JSONObject jsonObject) throws TravelAssistantException {return new TravelAssistantLocation(this, jsonObject);}
	public Location convertIp2Location(final AsyncCallback listener, final Object state)
	{
		if (listener != null) {
			new Thread() {
				public void run() {
					try {
						Location result = null;
						result = convertIp2Location(null, null);
						listener.onComplete(result, null);
					} catch (Exception e) {
						listener.onException(e, null);
					}
				}
			}.start();

			return null;
		} else {
			Location result = null;
			JSONObject jsonObject = new JSONObject();
			Hashtable params = new Hashtable();

			params.put("ak", TravelAssistantConfig.client_AK);

			try {
				jsonObject = doRequest(TravelAssistantConfig.queryIp2Location, params);

				result = (jsonObject != null ? convertIp2Location(jsonObject) : null);
			} catch (Exception e) {}

			return result;
		}
	}

	private SuggestionResult querySuggestLocation(JSONObject jsonObject) throws TravelAssistantException {return new TravelAssistantSuggestionResult(this, jsonObject);}
	public SuggestionResult querySuggestLocation(final String query, final String region, final AsyncCallback listener, final Object state)
	{
		if (listener != null) {
			new Thread() {
				public void run() {
					try {
						SuggestionResult result = null;
						result = querySuggestLocation(query, region, null, null);
						listener.onComplete(result, null);
					} catch (Exception e) {
						listener.onException(e, null);
					}
				}
			}.start();

			return null;
		} else {
			SuggestionResult result = null;
			JSONObject jsonObject = new JSONObject();
			Hashtable params = new Hashtable();

			params.put("query", query);
			params.put("region", region);
			params.put("output", "json");
			params.put("ak", TravelAssistantConfig.client_AK);

			try {
				jsonObject = doRequest(TravelAssistantConfig.querySuggestion, params);

				result = (jsonObject != null ? querySuggestLocation(jsonObject) : null);
			} catch (Exception e) {}

			return result;
		}
	}

	private Direction queryDirection(JSONObject jsonObject) throws TravelAssistantException {return new TravelAssistantDirection(this, jsonObject);}
	public Direction queryDirection(String mode, String region, String origin, String origin_region, String destination, String destination_region)
	{
		return queryDirection(mode, region, origin, origin_region, destination, destination_region, null, null);
	}
	public Direction queryDirection(final String mode, final String region, final String origin, final String origin_region, final String destination, final String destination_region, final AsyncCallback listener, final Object state)
	{
		if (listener != null) {
			new Thread() {
				public void run() {
					try {
						Direction result = null;
						result = queryDirection(mode, region, origin, origin_region, destination, destination_region, null, null);
						listener.onComplete(result, null);
					} catch (Exception e) {
						listener.onException(e, null);
					}
				}
			}.start();

			return null;
		} else {
			Direction result = null;
			JSONObject jsonObject = new JSONObject();
			Hashtable params = new Hashtable();

			params.put("mode", mode);
			params.put("origin", origin);
			params.put("origin_region", origin_region);
			params.put("destination", destination);
			params.put("destination_region", destination_region);
			params.put("region", region);
			params.put("output", "json");
			params.put("tactics", "11");
			params.put("ak", TravelAssistantConfig.client_AK);

			try {
				jsonObject = doRequest(TravelAssistantConfig.queryDirection, params);

				result = (jsonObject != null ? queryDirection(jsonObject) : null);
			} catch (Exception e) {}

			return result;
		}
	}

	private JSONObject doRequest(String api, Hashtable params) throws Exception
	{
		JSONObject result = null;
		StringBuffer responseBuffer = null;

		try {
			responseBuffer = checkResponse(_http.doGet(api, params));

			if ((responseBuffer == null) || (responseBuffer.length() <= 0))
			{
				result = null;
			} else {
				result = new JSONObject(new JSONTokener(new String(responseBuffer.toString().getBytes(), "utf-8")));
			}
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}

		return result;
	}

	private StringBuffer checkResponse(StringBuffer res) throws TravelAssistantException
	{
		if ((res != null) && (res.length() > 0))
		{
			if ((res.charAt(0) == '{') && (res.charAt(res.length() - 1) == '}'))
			{
//				JSONObject jsonObject;
//				try {
//					jsonObject = new JSONObject(new JSONTokener(res.toString()));
//
//					if (!jsonObject.optString("error_code").equals(""))
//					{
//						String error_msg = jsonObject.optString("error_msg");
//						String error_code = jsonObject.optString("error_code");
//						String from = jsonObject.optString("from");
//						String to = jsonObject.optString("to");
//						String query = jsonObject.optString("query");
//
//						if (error_code.equals("52001"))
//						{
//							Function.errorDialog("TIMEOUT：超时（52001）【请调整文本字符长度】");
//							return null;
//						} else if (error_code.equals("52002")) {
//							Function.errorDialog("SYSTEM ERROR：翻译系统错误（52002）");
//							return null;
//						} else if (error_code.equals("52003")) {
//							Function.errorDialog("UNAUTHORIZED USER：未授权的用户（52003）【请检查是否将api key输入错误】");
//							return null;
//						}
//
//						throw new TravelAssistantException("\u2022 error_code: " + error_code +
//													  "\n\u2022 error_msg: " + error_msg +
//													  "\n\u2022 from: " + from +
//													  "\n\u2022 to: " + to +
//													  "\n\u2022 query: " + query
//													 );
//					}
//				} catch (JSONException e) {}
			} else {
				throw new UnknownException(res.toString());
			}
		}

		return res;
	}
}